package com.hxci.service;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.alibaba.dashscope.utils.Constants;
import java.util.Arrays;

@Service
public class AiService {
    @Value("${dashscope.api.key:}")
    private String apiKey;

    public String chat(String prompt) {
        String key = System.getenv("DASHSCOPE_API_KEY");
        if (key == null || key.isEmpty()) {
            key = apiKey;
        }
        if (key != null && !key.isEmpty()) {
            Constants.apiKey = key;
        }
        try {
            Generation gen = new Generation();
            Message userMessage = Message.builder().role(Role.USER.getValue()).content(prompt).build();
            GenerationParam param = GenerationParam.builder().model("qwen-turbo").messages(Arrays.asList(userMessage)).resultFormat(GenerationParam.ResultFormat.MESSAGE).build();
            GenerationResult result = gen.call(param);
            return result.getOutput().getChoices().get(0).getMessage().getContent();
        } catch (Exception e) {
            return "错误:" + e.getMessage();
        }
    }
}